import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/components/shop_item.dart';
import 'package:cloud_medicine/components/shop_searchbar.dart';
import 'package:cloud_medicine/http/shop_api.dart';
import 'package:cloud_medicine/main.dart';
import 'package:cloud_medicine/model/base_user_info.dart';
import 'package:cloud_medicine/model/shop_list.dart';
import 'package:cloud_medicine/pages/my_collect.dart';
import 'package:cloud_medicine/pages/order_list.dart';
import 'package:cloud_medicine/pages/shop_detail.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:async';

class Medicine extends StatefulWidget {
  @override
  _MedicineState createState() => _MedicineState();
}

class _MedicineState extends State<Medicine> {
  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  List<ShopItem> _shoplist = [];
  bool _loading = false;
  bool showMoreLoading = false; // 上拉加载状态
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    // _scrollController.addListener(() {
    //   if (_scrollController.position.pixels ==
    //       _scrollController.position.maxScrollExtent) {
    //     _loadData();
    //   }
    // });
    _loadData();
  }

  // 加载中状态框
  Widget _buildProgressIndicator() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Center(
        child: Opacity(
          opacity: showMoreLoading ? 1.0 : 0.0,
          child: CircularProgressIndicator(),
        ),
      ),
    );
  }

  // 加载更多数据
  Future<Null> _loadData() async {
    setState(() {
      showMoreLoading = true;
    });
    dynamic res = await getShopList_api('$backIP/shop/shopList'); //接口路径
    res['data'].forEach((dynamic shopItem) {
      //遍历接口中的数据
      ShopItem shopItemModel = ShopItem.init(shopItem);
      _shoplist.add(shopItemModel);
    });
    if (mounted) {
      setState(() {
        showMoreLoading = false;
      });
    }
  }

  // 下拉刷新
  Future<Null> _refresh() async {
    setState(() {
      _shoplist.clear(); // 清除当前状态数据
      _loading = true;
    });

    dynamic res = await getShopList_api('$backIP/shop/shopList'); //接口路径
    res['data'].forEach((dynamic shopItem) {
      //遍历接口中的数据
      ShopItem shopItemModel = ShopItem.init(shopItem);
      _shoplist.add(shopItemModel);
    });
    setState(() {
      _loading = false;
    });
    Fluttertoast.showToast(
        msg: '刷新成功',
        backgroundColor: Colors.grey[300],
        textColor: Colors.lightBlueAccent);

    return;
  }

  popMenuItem(IconData icon, String text, String cvalue) {
    return PopupMenuItem<String>(
        value: cvalue,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[Icon(icon, color: Colors.blue), Text(text)],
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.grey[100],
        appBar: AppBar(
          automaticallyImplyLeading: false,
          title: ShopSearch(
            boxWidth: 180,
            hintTEXT: '搜药品/药店',
          ),
          centerTitle: true,
          actions: <Widget>[
            PopupMenuButton<String>(
              itemBuilder: (BuildContext context) {
                return <PopupMenuItem<String>>[
                  this.popMenuItem(Icons.chat, '消息', 'A'),
                  this.popMenuItem(Icons.content_paste, '订单', 'B'),
                  this.popMenuItem(Icons.stars, '收藏', 'C')
                ];
              },
              onSelected: (String action) {
                switch (action) {
                  case 'A':
                    {
                      if (user == null) {
                        Fluttertoast.showToast(
                          msg: '请先登录',
                          backgroundColor: Colors.black,
                          textColor: Colors.white,
                        );
                      } else {
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (context) => MyHomePage(
                                  initIndex: 2,
                                )));
                      }
                    }
                    break;
                  case 'B':
                    {
                      if (user == null) {
                        Fluttertoast.showToast(
                          msg: '请先登录',
                          backgroundColor: Colors.black,
                          textColor: Colors.white,
                        );
                      } else {
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (context) => OrderList()));
                      }
                    }
                    break;
                  case 'C':
                    {
                      if (user == null) {
                        Fluttertoast.showToast(
                          msg: '请先登录',
                          backgroundColor: Colors.black,
                          textColor: Colors.white,
                        );
                      } else {
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (context) => MyCollect()));
                      }
                    }
                    break;
                }
              },
            )
          ],
        ),
        body: RefreshIndicator(
          onRefresh: _refresh,
          color: Theme.of(context).primaryColor,
          displacement: 40, // 指示器显示时距顶部位置
          child: ListView.builder(
              shrinkWrap: true,
              controller: _scrollController,
              itemCount: _shoplist.length + 1,
              itemBuilder: (context, index) {
                if (index == _shoplist.length || _loading) {
                  return _buildProgressIndicator();
                } else {
                  return MyShopItem(
                    deliveryFee: _shoplist[index].deliveryFee,
                    grade: _shoplist[index].grade,
                    id: _shoplist[index].id,
                    img: _shoplist[index].image,
                    iniDeliveryFee: _shoplist[index].iniDeliveryFee,
                    name: _shoplist[index].name,
                    myonTap: () {
                      if (user == null) {
                        Fluttertoast.showToast(
                          msg: '请先登录',
                          backgroundColor: Colors.black,
                          textColor: Colors.white,
                        );
                        return;
                      } else {
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (context) => ShopDetail(
                                  shopid: _shoplist[index].id,
                                )));
                      }
                    },
                    padding: 10,
                  );
                }
              }),
        ));
  }
}
